package com.labichaoka.chaoka.ui.fetch;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.labichaoka.chaoka.BuildConfig;
import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseActivity;
import com.labichaoka.chaoka.base.GlobalParams;
import com.labichaoka.chaoka.entity.FetchMoneyRequest;
import com.labichaoka.chaoka.entity.FetchMoneyResponse;
import com.labichaoka.chaoka.entity.IsOpenAcountRequest;
import com.labichaoka.chaoka.entity.IsOpenAcountResponse;
import com.labichaoka.chaoka.entity.LimitStatusResponse;
import com.labichaoka.chaoka.ui.bank.bind.BankBindActivity;
import com.labichaoka.chaoka.ui.baseinfo.person.PersonInfoAdapter;
import com.labichaoka.chaoka.ui.web.WebViewActivity;
import com.labichaoka.chaoka.utils.DetectionUtil;
import com.labichaoka.chaoka.utils.ToastUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/*
 * 提现
 */

public class FetchMoneyActivity extends BaseActivity implements FetchMoneyView {

    @BindView(R.id.edit_amount)
    EditText editAmount;
    @BindView(R.id.use_time)
    TextView useTime;
    @BindView(R.id.next1)
    TextView next1;
    @BindView(R.id.how_use)
    TextView howUse;
    @BindView(R.id.next2)
    TextView next2;
    @BindView(R.id.commit)
    Button commit;
    @BindView(R.id.source)
    TextView source;
    @BindView(R.id.next3)
    TextView next3;
    @BindView(R.id.month)
    TextView month;
    @BindView(R.id.next4)
    TextView next4;
    @BindView(R.id.next6)
    TextView next6;
    @BindView(R.id.next7)
    TextView next7;
    @BindView(R.id.next8)
    TextView next8;
    @BindView(R.id.how_layout)
    RelativeLayout howLayout;

    @BindView(R.id.has_loan_layout)
    LinearLayout hasLoanLayout;
    @BindView(R.id.credit_layout)
    LinearLayout creditLayout;


    @BindView(R.id.loan_selected_img)
    ImageView loanSelectedImg;
    @BindView(R.id.loan_unselected_img)
    ImageView loanUnselectedImg;
    @BindView(R.id.loan_type)
    TextView loan_type;
    @BindView(R.id.loan_amount)
    EditText loanAmount;
    @BindView(R.id.credit_type)
    TextView creditType;
    @BindView(R.id.account)
    TextView account;
    @BindView(R.id.overdue_amount)
    EditText overdueAmount;
    @BindView(R.id.credit_selected_img)
    ImageView creditSelectedImg;
    @BindView(R.id.credit_unselected_img)
    ImageView creditUnselectedImg;
    private String availQuota;
    private String lendAmount;//借多少
    private String period;//用多久
    private String useForWhat; //怎么花
    private String repayType; //怎么还
    private String incomeResource;//收入来源
    private String monthlyIncome; //月收入水平
    private String hasLoan; //有无借贷
    private String loanMoney; //贷款金额
    private String overdueMoney; //逾期金额
    private String loanType; //贷款类型
    private String isHaveCreditRept; //有无征信报告
    private String overdueSituation; //近6个月的逾期情况
    private String overdueAccounts; //逾期账户数


    private TextView commonTv;

    private FetchMoneyPresenter presenter;
    private List<GlobalParams.Education> nperList;
    private List<GlobalParams.Education> list;
    private Dialog dialog;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_fetch_money;
    }

    @Override
    protected void initView() {
        next1.setTypeface(iconfont);
        next2.setTypeface(iconfont);
        next3.setTypeface(iconfont);
        next4.setTypeface(iconfont);
        next6.setTypeface(iconfont);
        next7.setTypeface(iconfont);
        next8.setTypeface(iconfont);
    }

    @Override
    protected void initData() {
        repayType = "每月等额";
        hasLoan="F2402";
        isHaveCreditRept="F2402";
        list = new ArrayList<>();
        dialog = new Dialog(mContext, R.style.Translucent_NoTitle);
        presenter = new FetchMoneyPresenterImpl(new FetchMoneyInteractorImpl(), this);
        presenter.calculate();

    }

    @OnClick({R.id.commit, R.id.use_layout, R.id.how_layout, R.id.source_layout, R.id.month_layout,
            R.id.loan_selected_layout, R.id.loan_unselected_layout, R.id.loan_type_layout, R.id.credit_selected_layout,
            R.id.credit_unselected_layout,R.id.credit_type_layout,R.id.overdue_layout
    })
    public void click(View v) {
        switch (v.getId()) {
            case R.id.commit:
                fetch();
                break;
            case R.id.use_layout:
                commonTv = useTime;
                initDialogData(0, "用多久");
                break;
            case R.id.how_layout:
                commonTv = howUse;
                initDialogData(1, "怎么用");
                break;
            case R.id.source_layout:
                commonTv = source;
                initDialogData(2, "收入来源");
                break;
            case R.id.month_layout:
                commonTv = month;
                initDialogData(3, "月收入水平");
                break;
            case R.id.loan_type_layout:
                commonTv = loan_type;
                initDialogData(4, "贷款类型");
                break;
            case R.id.credit_type_layout:
                commonTv = creditType;
                initDialogData(5, "近6个月逾期情况");
                break;
            case R.id.overdue_layout:
                commonTv = account;
                initDialogData(6, "逾期账户数");
                break;
            case R.id.loan_selected_layout:
                loanSelectedImg.setImageResource(R.mipmap.work_selected);
                loanUnselectedImg.setImageResource(R.mipmap.work_unselected);
                hasLoan = "F2401";
                hasLoanLayout.setVisibility(View.VISIBLE);
                checkButtonState();
                break;
            case R.id.loan_unselected_layout:
                loanSelectedImg.setImageResource(R.mipmap.work_unselected);
                loanUnselectedImg.setImageResource(R.mipmap.work_selected);
                hasLoan = "F2402";
                loanMoney="";
                loanAmount.setText("");
                loanType="";
                loan_type.setText("请选择");
                loan_type.setTextColor(getResources().getColor(R.color.font_909090));
                hasLoanLayout.setVisibility(View.GONE);
                checkButtonState();
                break;
            case R.id.credit_selected_layout:
                creditSelectedImg.setImageResource(R.mipmap.work_selected);
                creditUnselectedImg.setImageResource(R.mipmap.work_unselected);
                isHaveCreditRept = "F2401";
                creditLayout.setVisibility(View.VISIBLE);
                checkButtonState();
                break;
            case R.id.credit_unselected_layout:
                creditSelectedImg.setImageResource(R.mipmap.work_unselected);
                creditUnselectedImg.setImageResource(R.mipmap.work_selected);
                isHaveCreditRept = "F2402";
                overdueSituation="";
                creditType.setText("请选择");
                creditType.setTextColor(getResources().getColor(R.color.font_909090));
                overdueMoney="";
                overdueAmount.setText("");
                overdueAccounts="";
                account.setText("请选择");
                account.setTextColor(getResources().getColor(R.color.font_909090));
                creditLayout.setVisibility(View.GONE);
                checkButtonState();
                break;


        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        editAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                lendAmount = s.toString().trim();
                checkButtonState();
            }
        });

        loanAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                loanMoney= s.toString().trim();
                checkButtonState();
            }
        });

        overdueAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                overdueMoney = s.toString().trim();
                checkButtonState();
            }
        });

    }

    @Override
    public void showProgress() {
        showLoadingProgress();
    }

    @Override
    public void hideProgress() {
        hideLoadingProgress();
    }

    @Override
    public void showMessage(String str) {
        ToastUtils.show(str);
    }

    public void showBottomDialog(int type, String titleStr) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.person_info_dialog, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.showdialog);
        TextView close_icon = v.findViewById(R.id.close);
        TextView title = v.findViewById(R.id.title);
        RecyclerView recyclerView = v.findViewById(R.id.rv_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.divide_drawable));
        recyclerView.addItemDecoration(divider);

        title.setText(titleStr);
        close_icon.setTypeface(iconfont);
        close_icon.setOnClickListener((view) -> {
            dialog.dismiss();
        });


        PersonInfoAdapter adapter = new PersonInfoAdapter(mContext, list);
        recyclerView.setAdapter(adapter);


        adapter.setOnItemClickListener((position -> {
            dialog.dismiss();
            setValue(type, position);
        }));

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();

    }


    public void initDialogData(int type, String titleStr) {
        switch (type) {
            case 0:
                list = nperList;
                break;
            case 1:
                list = GlobalParams.getUseForWhat();
                break;
            case 2:
                list = GlobalParams.getIncome();
                break;
            case 3:
                list = GlobalParams.getIncomeByMonth();
                break;
            case 4:
                list = GlobalParams.getLoanType();
                break;
            case 5:
                list = GlobalParams.getCreditReport();
                break;
            case 6:
                list = GlobalParams.getOverdueAccount();
                break;
        }

        showBottomDialog(type, titleStr);
    }

    public void setValue(int type, int pos) {
        //设置提交的value
        switch (type) {
            case 0:
                period = nperList.get(pos).getId();
                break;
            case 1:
                useForWhat = list.get(pos).getId();
                break;
            case 2:
                incomeResource = list.get(pos).getId();
                break;
            case 3:
                monthlyIncome = list.get(pos).getId();
                break;
            case 4:
                loanType = list.get(pos).getId();
                break;
            case 5:
                overdueSituation = list.get(pos).getId();
                break;
            case 6:
                overdueAccounts = list.get(pos).getId();
                break;
        }
        checkButtonState();

        commonTv.setText(list.get(pos).getValue());
        commonTv.setTextColor(getResources().getColor(R.color.font_3a3a38));
    }


    public void checkButtonState() {

        if (TextUtils.isEmpty(lendAmount) || TextUtils.isEmpty(period)
                || TextUtils.isEmpty(useForWhat) || TextUtils.isEmpty(repayType) || TextUtils.isEmpty(incomeResource) ||
                TextUtils.isEmpty(monthlyIncome) ) {
            commit.setEnabled(false);
        } else if(hasLoan.equals("F2401")){
            if (TextUtils.isEmpty(loanMoney)||TextUtils.isEmpty(loanType)){
                commit.setEnabled(false);
            }else if(isHaveCreditRept.equals("F2401")){
                if (TextUtils.isEmpty(overdueSituation)||TextUtils.isEmpty(overdueAccounts)||TextUtils.isEmpty(overdueMoney)){
                    commit.setEnabled(false);
                }else{
                    commit.setEnabled(true);
                }
            }else{
                commit.setEnabled(true);
            }


        }else if(isHaveCreditRept.equals("F2401")){
            if (TextUtils.isEmpty(overdueSituation)||TextUtils.isEmpty(overdueAccounts)||TextUtils.isEmpty(overdueMoney)){
                commit.setEnabled(false);
            }else{
                commit.setEnabled(true);
            }
        }else{
            commit.setEnabled(true);
        }



    }

    public void fetch() {

        if (Double.parseDouble(lendAmount) > Double.parseDouble(availQuota)) {
            ToastUtils.show("输入金额有误!");
            return;
        } else if (Double.parseDouble(lendAmount) < 2000) {
            ToastUtils.show("提现需大于2000元!");
            return;
        }
        if(isHaveCreditRept.equals("F2401")){
            if (!DetectionUtil.isValidMoney(overdueMoney)){
                ToastUtils.show("逾期金额输入有误");
                return;
            }
            NumberFormat nf = new DecimalFormat("##.##");
            Double money = Double.parseDouble(overdueMoney);
            overdueMoney = nf.format(money);
        }



        FetchMoneyRequest request = new FetchMoneyRequest();
        request.setLendAmount(lendAmount);
        request.setPeriod(period);
        request.setUseForWhat(useForWhat);
        request.setRepayType(repayType);
        request.setIncomeResource(incomeResource);
        request.setMonthlyIncome(monthlyIncome);
        request.setHasLoan(hasLoan);
        request.setLoanType(loanType);
        request.setIsHaveCreditRept(isHaveCreditRept);
        request.setOverdueMoney(overdueMoney);
        request.setOverdueSituation(overdueSituation);
        request.setOverdueAccounts(overdueAccounts);
        request.setLoanMoney(loanMoney);

        presenter.commit(request);
    }


    @Override
    public void setData(LimitStatusResponse response) {
        nperList = response.getData().getSelectNper();
        availQuota = response.getData().getAvailQuota();
        editAmount.setHint("最多可提现" + availQuota);
    }

    @Override
    public void commit(FetchMoneyResponse response) {
        String keys = response.getData().getKeys();
        Bundle bundle = new Bundle();
        bundle.putString("keys", keys);
        bundle.putString("type", "2");
        gotoActivity(mContext, WebViewActivity.class, bundle);
        //下一步去那
    }

    @Override
    public void isOpenAcountCallback(IsOpenAcountResponse response) {
        if (response.getData() == null) {
            ToastUtils.show("获取数据异常，请稍后重试！");
            return;
        }
        String status = response.getData().getStatus();
        String openUrl = response.getData().getOpenUrl();//跳转认证地址
        String cardFlag = response.getData().getCardFlag();//1存在2不存在
        String cardSupport = response.getData().getCardSupport();//1支持2不支持


        String url = response.getData().getJumpUrl();

        if (TextUtils.isEmpty(status)) {
            ToastUtils.show("获取数据异常，请稍后重试！");
            return;
        }
        if (status.equals("1")) {
            //已开户
            if (TextUtils.isEmpty(cardFlag)) {
                ToastUtils.show("获取数据异常，请稍后重试！");
                return;
            }
            if (cardFlag.equals("1")) {
            } else {
                if (TextUtils.isEmpty(cardSupport)) {
                    ToastUtils.show("获取数据异常，请稍后重试！");
                    return;
                }
                showBankCheckDialog(cardSupport, openUrl);
            }
        } else {
            showSignDialog(url);
        }


    }

    private void showSignDialog(String url) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_sign_check, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);

        TextView ok = v.findViewById(R.id.ok);
        TextView cancel = v.findViewById(R.id.cancel);

        cancel.setOnClickListener(view -> {
                    dialog.dismiss();
                    finish();
                }
        );

        ok.setOnClickListener(view -> {
            dialog.dismiss();
            //开通存管户
            Bundle bundle = new Bundle();
            bundle.putString("type", "8");
            bundle.putString("url", url);
            gotoActivity(mContext, WebViewActivity.class, bundle);
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);

        dialog.show();

    }


    private void showBankCheckDialog(String status, String url) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_bank_check, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);

        TextView ok = v.findViewById(R.id.ok);
        TextView cancel = v.findViewById(R.id.cancel);

        cancel.setOnClickListener(view -> {
                    dialog.dismiss();
                    finish();
                }
        );

        ok.setOnClickListener(view -> {
            dialog.dismiss();
            if (status.equals("1")) {
                //开通存管户
                Bundle bundle = new Bundle();
                bundle.putString("type", "9");
                bundle.putString("url", url);
                gotoActivity(mContext, WebViewActivity.class, bundle);
            } else {
                Bundle bundle = new Bundle();
                bundle.putInt("type", GlobalParams.CHANGE_BANK_CARD);
                gotoActivity(mContext, BankBindActivity.class, bundle);
            }
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);

        dialog.show();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        IsOpenAcountRequest request = new IsOpenAcountRequest();
        request.setCallBackUrl(BuildConfig.WEB_HOST + "blankPage");
        presenter.isOpenAcount(request);
    }
}
